﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace vCrossPost.PingFM
{
    // Xml serialization stolen from Ping.fm API in C# library - Adam Duffy.
    public class Serialization
    {
        public static string GetChecksum(NameValueCollection values)
        {
            if (values == null) throw new ArgumentNullException("values");

            var sb = new StringBuilder();
            foreach (var key in values.AllKeys)
            {
                sb.Append(key);
                sb.Append(values[key]);
            }

            var bytes = Encoding.ASCII.GetBytes(sb.ToString());
            var hash = System.Security.Cryptography.MD5.Create().ComputeHash(bytes);
            var hashString = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

            return hashString;
        }

        public static string Base64Decode(string base64)
        {
            if (string.IsNullOrEmpty(base64))
                return string.Empty;

            var bytes = Convert.FromBase64String(base64);
            return Encoding.Default.GetString(bytes);
        }

        public static string Base64Encode(string unicode)
        {
            if (string.IsNullOrEmpty(unicode))
                return string.Empty;

            var bytes = Encoding.UTF8.GetBytes(unicode);
            return Convert.ToBase64String(bytes);
        }

        public static T Deserialize<T>(Stream stream)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stream);
        }
    }

    [XmlRoot("rsp")]
    public class LatestResponse : PingResponse
    {
        [XmlArray("messages"), XmlArrayItem("message", typeof(Message))]
        public List<Message> Messages = new List<Message>();

        public void DecodeMessages()
        {
            if (Messages == null) return;
            foreach (var m in Messages)
                m.Decode();
        }
    }

    public class Message
    {
        [XmlElement("content")]
        public PingContent Content;

        [XmlElement("date")]
        public PingDate Date;

        [XmlAttribute("id")]
        public string ID;

        [XmlAttribute("method")]
        public string Method;

        [XmlArray("services"), XmlArrayItem("service", typeof(Service))]
        public List<Service> Services = new List<Service>();

        public void Decode()
        {
            Content.Body = Serialization.Base64Decode(Content.Body);
            Content.Title = Serialization.Base64Decode(Content.Title);
        }

        public override string ToString()
        {
            if (!string.IsNullOrEmpty(Method))
                return Method;

            return base.ToString();
        }

        #region Nested type: PingContent

        public struct PingContent
        {
            [XmlElement("body")]
            public string Body;

            [XmlElement("title")]
            public string Title;

            public override string ToString()
            {
                if (!string.IsNullOrEmpty(Title))
                    return Title;

                if (!string.IsNullOrEmpty(Body))
                    return Body;

                return base.ToString();
            }
        }

        #endregion

        #region Nested type: PingDate

        public struct PingDate
        {
            [XmlAttribute("rfc")]
            public string Date;

            [XmlAttribute("unix")]
            public long Unix;

            public override string ToString()
            {
                return Date;
            }
        }

        #endregion
    }

    [XmlRoot("rsp")]
    public class MessageResponse : PingResponse
    {
        [XmlElement("message")]
        public new Message Message;
    }

    [XmlRoot("rsp")]
    public class PingResponse
    {
        [XmlElement("message")]
        public string Message;

        [XmlElement("method")]
        public string Method;

        [XmlAttribute("status")]
        public string Status;

        [XmlElement("transaction")]
        public string Transaction;
    }

    public class Service
    {
        [XmlAttribute("id")]
        public string ID;

        [XmlElement("methods")]
        public string Methods;

        [XmlAttribute("name")]
        public string Name;

        public override string ToString()
        {
            if (!string.IsNullOrEmpty(Name))
                return string.Concat(Name, " [", ID, "]");

            return base.ToString();
        }
    }

    [XmlRoot("rsp")]
    public class ServicesResponse : PingResponse
    {
        [XmlArray("services"), XmlArrayItem("service", typeof(Service))]
        public List<Service> Services;
    }

    public class Trigger
    {
        [XmlAttribute("id")]
        public string ID;

        [XmlAttribute("method")]
        public string Method;

        [XmlArray("services"), XmlArrayItem("service", typeof(Service))]
        public List<Service> Services = new List<Service>();

        public override string ToString()
        {
            if (!string.IsNullOrEmpty(ID))
                return string.Concat(ID, " (", Method, ")");

            return base.ToString();
        }
    }

    [XmlRoot("rsp")]
    public class TriggerResponse : PingResponse
    {
        [XmlArray("triggers"), XmlArrayItem("trigger", typeof(Trigger))]
        public List<Trigger> Triggers;
    }
}